package com.cgly.medical.security;

import com.cgly.medical.domain.RolePath;
import com.cgly.medical.service.PathService;
import com.cgly.medical.service.impl.PathServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @program: CGLY
 * @description:
 * @author: chen di
 * @create: 2022-08-28 23:06
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    PathService pathService;//查询数据库中url与role的关系

    /**
     * 所有非ignore请求进来第一步 --->Manager
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {


        AntPathMatcher antPathMatcher = new AntPathMatcher();

        //获取请求地址，判断是否是管理员才能访问
        String requestUrl = ((FilterInvocation) object).getRequestUrl();//获取当前的请求地址
        List<RolePath> rolePaths = pathService.getPath();
        for (RolePath rolePath : rolePaths) {
            if (antPathMatcher.match(rolePath.getPath(), requestUrl)) {
                return SecurityConfig.createList(rolePath.getRoleName() );
            }

        }
//        return SecurityConfig.createList("ROLE_2");
        return SecurityConfig.createList("ROLE_0");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}